package com.link.base.base.errorcode.service;

import com.link.base.base.errorcode.dao.mybatis.mapper.ErrorCodeMessageMapper;
import com.link.base.base.errorcode.model.ErrorCodeMessage;
import com.link.base.base.errorcode.model.ErrorCodeSimple;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.RedisUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 错误编码信息维护
 *
 * @author cuizhiyong
 * @date 2019/4/25 19:07
 */
@Service
public class ErrorCodeMessageServiceImpl extends BasicServiceImpl<ErrorCodeMessage> implements ErrorCodeMessageService {

    private static String LNK_ERROR_CODE_KEY = "LINKCRM_KEY_OF_ERROR_CODE_CACHE";

    @Resource
    private ErrorCodeMessageMapper errorCodeMessageMapper;

    @Override
    public BasicMapper<ErrorCodeMessage> getBasicMapper() {
        return errorCodeMessageMapper;
    }

    @Override
    public void refreshRedisCache() {
        List<ErrorCodeSimple> list = errorCodeMessageMapper.queryCacheData();
        LinkRedisClient jedis = RedisUtil.getJedis();
        try {
            // 清除错误信息缓存
            jedis.del(LNK_ERROR_CODE_KEY);
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            // 错误编码和语言具有唯一性，以两个字段未主键将错误信息放入redis中缓存
            list.forEach(item -> {
                // 使用JSON对象封装数据，防止 "错误内容" 解析异常，也便于异常信息字段的增减
                jedis.hset(LNK_ERROR_CODE_KEY,
                        item.getErrorCode() + item.getErrorLang(),
                        item.getErrorLevel() + "&" + item.getErrorMessage());
            });
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    @Override
    public boolean duplicateValidate(ErrorCodeMessage errorCodeMessage) {
        return errorCodeMessageMapper.duplicateValidate(errorCodeMessage) > 0;
    }

}
